// src/routes/api.js

const express = require('express');


const { Circle, Product, ProductTags, Series, Tag, VA, sequelize, Op } = require('../models');
const FileScanner = require('../services/fileScanner');
const DLsiteScraper = require('../services/dlsiteScraper');
const EditConfig = require('../config/editConfig');
const ProductService = require('../services/productService')

const editConfig = new EditConfig();

const router = express.Router();

router.get('/config/fetchConfig', (req, res) => {
    const config = editConfig.readConfig();
    // console.log('config: ', config);
    return res.status(200).json(config);
});

router.post('/config/addFolder', (req, res) => {
    const { folderName, folderPath } = req.body;
    console.log({ folderName, folderPath });
    // 检查请求的内容
    if (folderName && folderPath) {
        editConfig.setScanFolder({ folderName, folderPath });
        return res.status(200).json({ message: '文件夹添加成功' });
    } else {
        return res.status(400).json({ error: '文件路径不合规' });
    }

});

router.post('/config/setProxy', (req, res) => {
    const { proxyIP, proxyPort } = req.body;
    console.log({ proxyIP, proxyPort });
    // 检查请求的内容
    if (proxyIP && proxyPort) {
        editConfig.setProxy({ proxyIP, proxyPort });
        return res.status(200).json({ message: '代理地址设置成功' });
    } else {
        return res.status(400).json({ error: '代理设置不合规' });
    }
});

router.post('/config/removeFolder', (req, res) => {
    const { index } = req.body;
    editConfig.removeScanFolder(index);
    return res.status(200).json({ message: '移除文件夹成功' });
});

// 扫描和更新数据库的路由
router.post('/scan', async (req, res) => {
    const { scanPath } = req.body;
    console.log('PATH ', scanPath);
    const fileScanner = new FileScanner(scanPath);
    const proxy = 'http://' + editConfig.readConfig().proxyIP + ':' + editConfig.readConfig().proxyPort;
    const dlsiteScraper = new DLsiteScraper(proxy);
    const productService = new ProductService();

    let countFail = 0;
    let countJump = 0;

    const results = await fileScanner.scan();
    for (const result of results) {
        try {
            console.log('\x1b[35m%s\x1b[0m', `开始扫描 ${result.path}，识别出 ${result.code}`);
            let productData = null;

            const product = await Product.findOne({
                where: {
                    rjCode: result.code
                }
            })
            if (product) {
                countJump++;
                console.log('\x1b[35m%s\x1b[0m', `${result.code} 已存在，跳过爬虫`);
            } else {
                productData = await dlsiteScraper.scrapeProduct(result.code);
            }

            // console.log('productInfo是:', productInfo);

            if (productData) {
                // 调用函数插入数据
                await productService.insertProductData(productData, result);
            }
        } catch (error) {
            console.error('Error during scan:', error);
            countFail++;
        }
    }

    res.json({ message: `扫描完成, 成功${results.length - countFail - countJump}个，跳过${countJump}个，失败${countFail}个` });

});

// 获取所有产品的路由
router.get('/products', async (req, res) => {
    try {
        const { search, current, pageSize } = req.query;
        const productService = new ProductService();
        let where = {};
        // console.log('//////////////////////////////////////////////////////////', search)
        if (search) {
            where = { title: { [Op.like]: `%${search}%` } }
        }

        const result = await productService.getAllProducts({
            current,
            pageSize,
            orderBy: 'createdAt',
            order: 'DESC',
            filter: {}
        });
        console.log('----------------------------------------------------------------------', result)
        res.json({ total: result.total, result: result.products });
    } catch (error) {
        console.error('Error fetching products:', error);
        res.status(500).json({ error: 'An error occurred while fetching products' });
    }
});

// 获取tags的路由
router.get('/tags', async (req, res) => {
    try {
        const { search } = req.query;
        let where = {};
        if (search) {
            where = { name: { [Op.like]: `%${search}%` } }
        }
        // 并行查询所有产品、社团和标签
        const [tags, productTags] = await Promise.all([
            Tag.findAll({
                attributes: ['id', 'name'],
                where,
                raw: true
            }),
            ProductTags.findAll({
                attributes: ['tagID', [sequelize.fn('COUNT', sequelize.col('tagID')), 'count']],
                order: [['count', 'DESC']],
                group: ['tagID'],
                raw: true
            })
        ]);

        // 创建一个 Map，用来根据 tagID 找到对应的标签名称
        const tagMap = new Map();
        tags.forEach(tag => {
            tagMap.set(tag.id, tag.name);
        });

        const result = productTags
            .map(pt => {
                const tagName = tagMap.get(pt.tagID);
                if (tagName) { // 只在 tagName 存在时返回对象
                    return {
                        name: tagName,
                        count: pt.count
                    };
                }
                return null; // 否则返回 null 表示无效
            })
            .filter(item => item !== null); // 过滤掉无效的项
        res.json(result);
    } catch (error) {
        console.error('获取tags时出错：', error);
        res.status(500).json({ error: '获取tags时出错' });
    }
});

// 获取vas的路由
router.get('/vas', async (req, res) => {
    try {
        const { search } = req.query;
        let where = {};
        if (search) {
            where = { name: { [Op.like]: `%${search}%` } }
        }

        const vas = await VA.findAll({
            attributes: [
                'name',
                [sequelize.fn('COUNT', sequelize.col('name')), 'count']
            ],
            where,
            group: ['name'],
            order: [['count', 'DESC']],
            raw: true
        })
        res.json(vas);
    } catch (error) {
        console.error('获取vas时出错：', error);
        res.status(500).json({ error: '获取vas时出错' });
    }
});

// 获取circles的路由
router.get('/circles', async (req, res) => {
    try {
        const { search } = req.query;
        let where = {};
        if (search) {
            where = { name: { [Op.like]: `%${search}%` } }
        }

        // 并行查询所有产品、社团和标签
        const [products, circles] = await Promise.all([
            Product.findAll({
                attributes: ['circleID', [sequelize.fn('COUNT', sequelize.col('circleID')), 'count']],
                order: [['count', 'DESC']],
                group: ['circleID'],
                raw: true
            }),
            Circle.findAll({
                attributes: ['id', 'name'],
                where,
                raw: true
            })
        ]);

        // 创建一个 Map，用来根据 tagID 找到对应的标签名称
        const circleMap = new Map();
        circles.forEach(circle => {
            circleMap.set(circle.id, circle.name);
        });

        const result = products
            .map(product => {
                const circleName = circleMap.get(product.circleID);
                if (circleName) { // 只在 tagName 存在时返回对象
                    return {
                        name: circleName,
                        count: product.count
                    };
                }
                return null; // 否则返回 null 表示无效
            })
            .filter(item => item !== null); // 过滤掉无效的项

        res.json(result);
    } catch (error) {
        console.error('获取circles时出错：', error);
        res.status(500).json({ error: '获取circles时出错' });
    }
});


module.exports = router;